//
//  NotificationViewController.m
//  Contractor
//
//  Created by 金鑫 on 16/5/3.
//  Copyright © 2016年 star j. All rights reserved.
//

#import "NotificationViewController.h"
#import "NoticeModel.h"
#import "NoticeTableViewCell.h"
#import "DetailNoticeViewController.h"
#import "CONST.h"
#import "MBProgressHUD.h"

@interface NotificationViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSMutableArray *noticArray ;
    UITableView *NoticeList ;
    UIView *nullView ;
}


@end

@implementation NotificationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor] ;
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.edgesForExtendedLayout = UIRectEdgeBottom | UIRectEdgeLeft | UIRectEdgeRight;
    self.navigationItem.title = @"我的通知" ;
    noticArray = [NSMutableArray array] ;
    [self downloadData] ;
    [self createTableview] ;

}

#pragma mark - 加载数据
- (void)downloadData
{
    [nullView removeFromSuperview] ;
    [NoticeList reloadData] ;
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = NSLocalizedString(@"正在努力加载...", @"HUD loading title") ;
    
    NSUserDefaults *uidDefaults = [NSUserDefaults standardUserDefaults] ;
    NSInteger uidInt = [[uidDefaults valueForKey:@"uid"] integerValue] ;
    
    NSNumber *cmd = [[NSNumber alloc] initWithInt:15] ;
    NSNumber *uid = [[NSNumber alloc] initWithInteger:uidInt] ;
    
    NSNumber *status = [[NSNumber alloc] initWithInt:2] ;
    NSNumber *pagenum = [[NSNumber alloc] initWithInt:0] ;
    NSNumber *rownum = [[NSNumber alloc] initWithInt:10] ;
    NSNumber *lastinfoid = [[NSNumber alloc] initWithInt:0] ;
    
    
    NSDictionary *jsondic = @{@"msgtype":status,
                              @"pagenum":pagenum,    //页数
                              @"rownum":rownum,    //每页显示数量
                              @"lastgdorderinfoid":lastinfoid    //上页最小 id
                              } ;
    NSString *jsonstr =  [CodeWithDES encodeWithDic:jsondic] ;
    NSLog(@"%@",jsondic) ;
    NSLog(@"%@",jsonstr) ;
    NSDictionary *parameters = @{@"cmd":cmd, @"uid":uid, @"jsonstr":jsonstr};
    NSLog(@"%@",parameters) ;
    
    // NSDictionary *parameters = @{@"cmd":cmd, @"uid":uid};
    // NSLog(@"parameters:%@",parameters) ;
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:getAppJson parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         //解密并解析json数据，将json转成字典
         NSString *decodeStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] ;
         NSLog(@"decodeStr:%@",decodeStr) ;
         decodeStr = [CodeWithDES decodeWithStr:decodeStr] ;
         NSLog(@"decodeStr:%@",decodeStr) ;
         NSData *decodeData = [decodeStr dataUsingEncoding:NSUTF8StringEncoding] ;
         id result = [NSJSONSerialization JSONObjectWithData:decodeData options:NSJSONReadingMutableContainers error:nil] ;
         //获取字典中的值
         if ([result isKindOfClass:[NSDictionary class]])
         {
             [hud hideAnimated:YES] ;
             NSDictionary *dic = result ;
             NSArray *content = dic[@"content"] ;
             if (content.count != 0) {
                 for (NSDictionary *contentDic in content) {
                     NoticeModel *model = [[NoticeModel alloc] init] ;
                     [model setValuesForKeysWithDictionary:contentDic] ;
                     model.noticeid = contentDic[@"id"] ;
                     [noticArray addObject:model] ;
                 }
             }
             if (noticArray.count == 0) {
                 [self createNullView] ;
             }
             else
             {
                 [nullView removeFromSuperview] ;
             }

             NSLog(@"通知:%@",dic) ;
             [NoticeList reloadData] ;
         }
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [hud hideAnimated:YES] ;
         NSLog(@"Error: %@", error);
     }];
}

#pragma mark - 创建NullView
- (void)createNullView
{
    nullView = [[UIView alloc] initWithFrame:CGRectMake(0, 51, __kScreenWidth, self.view.frame.size.height - 110)] ;
    nullView.backgroundColor = [UIColor whiteColor] ;
    [self.view addSubview:nullView] ;
    
    UIImageView *pageLoadingImageView = [[UIImageView alloc] initWithFrame:CGRectMake(__kScreenWidth / 4, (nullView.frame.size.height - __kScreenWidth/2) / 3, __kScreenWidth / 2, __kScreenWidth / 2)] ;
    [pageLoadingImageView setImage:[UIImage imageNamed:@"page_loading_szn_green_icon.png"]] ;
    [nullView addSubview:pageLoadingImageView] ;
    
    UILabel *label = [[UILabel alloc] init] ;
    label.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:18.0f] ;
    label.backgroundColor = [UIColor clearColor] ;
    label.textAlignment = NSTextAlignmentCenter ;
    label.textColor = [UIColor grayColor] ;
    label.frame = CGRectMake(0, pageLoadingImageView.frame.origin.y + pageLoadingImageView.frame.size.height + 10, __kScreenWidth, 20.0f) ;
    label.text = @"哎呀，暂时没有任何内容哦！" ;
    [nullView addSubview:label] ;
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom] ;
    [btn setTitle:@"重新加载" forState:UIControlStateNormal] ;
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal] ;
    btn.titleLabel.font = [UIFont fontWithName:@"Arial-BoldMT" size:14.0f] ;
    [btn setBackgroundImage:[UIImage imageNamed:@"afresh_loading_btn_normal_bg.png"] forState:UIControlStateNormal] ;
    btn.frame = CGRectMake((__kScreenWidth - 80) / 2, label.frame.origin.y + label.frame.size.height + 10, 80, 30) ;
    [btn addTarget:self action:@selector(downloadData) forControlEvents:UIControlEventTouchUpInside] ;
    
    [nullView addSubview:btn] ;
}


#pragma mark - 创建tableview
- (void)createTableview
{
    NoticeList = [[UITableView alloc] initWithFrame:CGRectMake(0, self.view.frame.origin.y + 2, self.view.frame.size.width, self.view.frame.size.height-65) style:UITableViewStylePlain] ;
    NoticeList.separatorStyle = UITableViewCellSeparatorStyleNone ;
    NoticeList.showsVerticalScrollIndicator = NO;
    NoticeList.scrollEnabled = YES ;
    NoticeList.delegate = self ;
    NoticeList.dataSource = self ;
    [self.view addSubview:NoticeList] ;
    
}

#pragma mark - tableviewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1 ;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return noticArray.count ;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NoticeTableViewCell *cell = [NoticeTableViewCell cellWithTableView:tableView] ;
    cell.selectionStyle = UITableViewCellSelectionStyleNone ;
    
    [cell config:noticArray[indexPath.row]] ;
    
    return cell ;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70 ;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailNoticeViewController *vc = [[DetailNoticeViewController alloc] init] ;
    vc.model = noticArray[indexPath.row] ;
    self.hidesBottomBarWhenPushed = YES ;
    [self.navigationController pushViewController:vc animated:NO] ;
    
}


- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO ;
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES ;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
